package LeetCode;

import java.util.ArrayList;
import java.util.List;

public class No56 {
    public static void main(String[] args) {
        int[][] a ={{1,4},{2,3}};
        int[][] b = merge(a);
        for (int i = 0; i < b.length; i++) {
            System.out.println(b[i][0] + " " + b[i][1]);
        }
    }

    public static int[][] merge(int[][] intervals) {
        List<Integer[]> list = new ArrayList<>();
        int [][] b = new int[intervals.length][2];
        int length = 0;
        for (int i = 0; i < intervals.length; i++) {
            for (int j = 0; j < intervals.length-i-1; j++) {
                if(intervals[j][0]>intervals[j+1][0]){
                    int[] a = intervals[j];
                    intervals[j] = intervals[j+1];
                    intervals[j+1] = a;
                }
            }
        }
        int l;
        for (int i = 0; i < intervals.length; i++) {
            //System.out.println(intervals[i][0]+" "+intervals[i][1]);
            Integer[] list1 = new Integer[2];
            list1[0]=intervals[i][0];
            l=i+1;
            while(l<intervals.length&&intervals[i][1]>=intervals[l][0]){
                //System.out.println(intervals[i][1]+" "+intervals[l][1]);
                intervals[i][1]=Math.max(intervals[l][1],intervals[i][1]);
                intervals[l][1]=Math.max(intervals[l][1],intervals[i][1]);
                l++;
            }
            i=l-1;
            list1[1] = intervals[i][1];
            list.add(list1);
            //System.out.println(list1[0]+" "+list1[1]);
        }
        int[][] result = new int[list.size()][2];
        int n = 0;
        for (Integer[] a: list) {
            result[n][0] = a[0];
            result[n][1] = a[1];
            n++;
        }

        return result;
    }
}
